package com.ruoyi.web.controller.system;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.AliyunSmsUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.CamsEnrollInfo;
import com.ruoyi.system.domain.CamsRecord;
import com.ruoyi.system.domain.dto.EnrollDto;
import com.ruoyi.system.domain.vo.ActivityVo;
import com.ruoyi.system.domain.vo.CamsActivityVo;
import com.ruoyi.system.domain.vo.CamsEnrollInfoVo;
import com.ruoyi.system.service.ICamsEnrollInfoService;
import com.ruoyi.system.service.ICamsRecordService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CamsActivity;
import com.ruoyi.system.service.ICamsActivityService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 校园活动Controller
 *
 * @author anskory
 * @date 2024-04-07
 */
@RestController
@RequestMapping("/system/activity")
public class CamsActivityController extends BaseController {
    @Autowired
    private ICamsActivityService camsActivityService;


    @Autowired
    private ICamsEnrollInfoService camsEnrollInfoService;

    @Autowired
    private ICamsRecordService camsRecordService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询校园活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/list")
    public TableDataInfo list(CamsActivity camsActivity) {

        startPage();
        List<CamsActivity> list = camsActivityService.selectCamsActivityList(camsActivity);
        return getDataTable(list);
    }

    /**
     * 导出校园活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:export')")
    @Log(title = "校园活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CamsActivity camsActivity) {
        List<CamsActivity> list = camsActivityService.selectCamsActivityList(camsActivity);
        ExcelUtil<CamsActivity> util = new ExcelUtil<CamsActivity>(CamsActivity.class);
        util.exportExcel(response, list, "校园活动数据");
    }

    /**
     * 导出报名数据
     */
    @Log(title = "报名数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export/enroll")
    public void exportEnroll(HttpServletResponse response, String id) {
        CamsActivity camsActivity = camsActivityService.getById(id);
        List<CamsEnrollInfo> list = camsEnrollInfoService.list(new LambdaQueryWrapper<CamsEnrollInfo>().eq(CamsEnrollInfo::getActivityId, id));
        List<EnrollDto> listVo = new ArrayList<>();
        //将list拷贝到listVo
        list.forEach(item -> {
            EnrollDto vo = new EnrollDto();
            BeanUtils.copyProperties(item, vo);
            vo.setActivityTitle(camsActivity.getTitle());
            vo.setUserNick(sysUserService.selectUserByUserName(item.getUsername()).getUserName());
            vo.setIsSignIn(item.getSignInTime() != null?"是":"否");
            vo.setSignInTime(item.getSignInTime());
            vo.setActivityId(camsActivity.getId());
            listVo.add(vo);
        });
        ExcelUtil<EnrollDto> util = new ExcelUtil<EnrollDto>(EnrollDto.class);
        util.exportExcel(response, listVo, camsActivity.getTitle() + "报名数据");
    }

    /**
     * 获取校园活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:activity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(camsActivityService.getById(id));
    }

    /**
     * 新增校园活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:add')")
    @Log(title = "校园活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CamsActivity camsActivity) {
        if (camsActivity.getResponsiblePerson() == null) {
            camsActivity.setResponsiblePerson(SecurityUtils.getNickname());
        }
        camsActivity.setCreateBy(SecurityUtils.getUsername());
        return toAjax(camsActivityService.save(camsActivity));
    }

    /**
     * 修改校园活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:edit')")
    @Log(title = "校园活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CamsActivity camsActivity) {
        if (camsActivity.getResponsiblePerson() == null) {
            camsActivity.setResponsiblePerson(SecurityUtils.getNickname());
        }
        camsActivity.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(camsActivityService.updateById(camsActivity));
    }

    /**
     * 删除校园活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:remove')")
    @Log(title = "校园活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(camsActivityService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 发布校园活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:release')")
    @Log(title = "校园活动", businessType = BusinessType.UPDATE)
    @PutMapping("/release/{id}")
    public AjaxResult edit(@PathVariable String id) {
        CamsActivity activity = camsActivityService.getById(id);
        System.out.println(DateUtils.getNowDate());
        System.out.println(activity.getActivityStartTime());
        if (activity.getReleaseStatus()) {
            return AjaxResult.warn("该活动已发布，请勿重复发布");
        }
        if (activity.getActivityStartTime().before(DateUtils.getNowDate())) {
            return AjaxResult.warn("活动开始时间已过，请重新设置活动开始时间");
        }
        if (activity.getActivityEndTime().before(DateUtils.getNowDate())) {
            return AjaxResult.warn("活动结束时间已过，请重新设置活动结束时间");
        }
        if (activity.getActivityEndTime().before(activity.getActivityStartTime())) {
            return AjaxResult.warn("活动结束时间不能小于活动开始时间，请重新设置活动结束时间");
        }
        if (activity.getEndTime().before(DateUtils.getNowDate())) {
            return AjaxResult.warn("报名截止时间已过，请重新设置报名截止时间");
        }
        if (activity.getUpperLimit() == null) {
            return AjaxResult.warn("请设置活动人数上限");
        }

        CamsActivity camsActivity = new CamsActivity();
        camsActivity.setId(id);
        camsActivity.setReleaseStatus(true);
        camsActivity.setReleaseTime(DateUtils.getNowDate());
        return toAjax(camsActivityService.updateById(camsActivity));
    }

    /**
     * 取消发布校园活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:cancelRelease')")
    @Log(title = "校园活动", businessType = BusinessType.UPDATE)
    @PutMapping("/cancelRelease/{id}")
    public AjaxResult cancelRelease(@PathVariable String id) {
        CamsActivity activity = camsActivityService.getById(id);
        if (!activity.getReleaseStatus()) {
            return AjaxResult.warn("该活动未发布，请勿重复取消发布");
        }

        if (activity.getActivityEndTime().before(DateUtils.getNowDate())) {
            return AjaxResult.warn("活动已结束");
        }
        CamsActivity camsActivity = new CamsActivity();
        camsActivity.setId(id);
        camsActivity.setReleaseStatus(false);
        camsActivity.setReleaseTime(null);
        LambdaQueryWrapper<CamsEnrollInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CamsEnrollInfo::getActivityId, id);
        camsEnrollInfoService.remove(queryWrapper);
        return toAjax(camsActivityService.updateById(camsActivity));
    }

    /**
     * 获取已发布活动列表
     */
    @GetMapping("/releaseList")
    public TableDataInfo releaseList(String keyword) {
        startPage();
        LambdaQueryWrapper<CamsActivity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CamsActivity::getReleaseStatus, true);
        if (keyword != null) {
            queryWrapper.and(wrapper -> wrapper.like(CamsActivity::getTitle, keyword).or().like(CamsActivity::getOutline, keyword).or().like(CamsActivity::getResponsiblePerson, keyword));
        }
        queryWrapper.orderByDesc(CamsActivity::getReleaseTime);
        List<CamsActivity> list = camsActivityService.list(queryWrapper);
        list.forEach(x -> {
            camsActivityService.releaseDetail(x);
        });
        return getDataTable(list);
    }

    /**
     * 获取已发布活动详情
     */
    @GetMapping("/releaseDetail/{id}")
    public AjaxResult releaseDetail(@PathVariable String id) {
        CamsActivity activity = camsActivityService.getById(id);
        if (activity == null || !activity.getReleaseStatus()) {
            return AjaxResult.error("活动不存在");
        }
        camsRecordService.addOrUpdateRecord(id, 0);
        CamsActivity camsActivity = camsActivityService.releaseDetail(activity);
        camsActivity.setSignInCount((int) camsEnrollInfoService.count(new LambdaQueryWrapper<CamsEnrollInfo>().eq(CamsEnrollInfo::getActivityId, id)));
        camsActivity.setIsSignUp(0 < camsEnrollInfoService.count(new LambdaQueryWrapper<CamsEnrollInfo>().eq(CamsEnrollInfo::getActivityId, id).eq(CamsEnrollInfo::getUsername, SecurityUtils.getUsername())));
        return success(camsActivity);
    }

    /**
     * 获取报名列表
     */
    @GetMapping("/signUpList")
    public TableDataInfo signUpList(String keyword) {
        startPage();
        List<ActivityVo> list = camsActivityService.signUpList(keyword);
        return getDataTable(list);
    }

    /**
     * 报名
     */
    @PutMapping("/signUp/{id}")
    public AjaxResult signUp(@PathVariable String id) {
        return camsActivityService.signUp(id);
    }

    /**
     * 取消报名
     */
    @PutMapping("/cancelSignUp/{id}")
    public AjaxResult cancelSignUp(@PathVariable String id) {
        LambdaQueryWrapper<CamsEnrollInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CamsEnrollInfo::getActivityId, id);
        queryWrapper.eq(CamsEnrollInfo::getUsername, SecurityUtils.getUsername());
        if (camsEnrollInfoService.count(queryWrapper) == 0) {
            return AjaxResult.error("未报名");
        }
        return toAjax(camsEnrollInfoService.remove(queryWrapper));
    }

    /**
     * 签到
     */
    @PutMapping("/signIn/{id}")
    public AjaxResult signIn(@PathVariable String id) {
        LambdaQueryWrapper<CamsActivity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CamsActivity::getId, id);
        if (camsActivityService.getOne(queryWrapper).getStartTime().after(DateUtils.getNowDate())) {
            return AjaxResult.error("活动未开始！");
        }
        if (camsActivityService.getOne(queryWrapper).getEndTime().before(DateUtils.getNowDate())) {
            return AjaxResult.error("活动已结束！");
        }
        CamsEnrollInfo camsEnrollInfo = new CamsEnrollInfo();
        camsEnrollInfo.setActivityId(id);
        camsEnrollInfo.setUsername(SecurityUtils.getUsername());
        camsEnrollInfo.setSignInTime(DateUtils.getNowDate());
        return toAjax(camsEnrollInfoService.updateById(camsEnrollInfo));
    }

    /**
     * 获取报名信息
     */
    @GetMapping("/signUpInfo/{id}")
    public AjaxResult signUpInfo(@PathVariable String id) {
        ActivityVo activityVo = new ActivityVo();
        LambdaQueryWrapper<CamsEnrollInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CamsEnrollInfo::getActivityId, id);
        queryWrapper.eq(CamsEnrollInfo::getUsername, SecurityUtils.getUsername());
        CamsEnrollInfo camsEnrollInfo = camsEnrollInfoService.getOne(queryWrapper);
        if (camsEnrollInfo == null) {
            return AjaxResult.error("未报名");
        } else {
            LambdaQueryWrapper<CamsActivity> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(CamsActivity::getId, id);
            CamsActivity camsActivity = camsActivityService.getOne(queryWrapper1);
            BeanUtils.copyProperties(activityVo, camsActivity);
            activityVo.setEnrollInfo(camsEnrollInfo);
        }
        return success(activityVo);
    }

    /**
     * 获取报名状态
     */
    @GetMapping("/signUpStatus/{id}")
    public R signUpStatus(@PathVariable String id) {
        LambdaQueryWrapper<CamsEnrollInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CamsEnrollInfo::getActivityId, id);
        queryWrapper.eq(CamsEnrollInfo::getUsername, SecurityUtils.getUsername());
        CamsEnrollInfo camsEnrollInfo = camsEnrollInfoService.getOne(queryWrapper);
        if (camsEnrollInfo == null) {
            return R.ok();
        } else {
            return R.ok(camsEnrollInfo);
        }
    }


}
